/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shellCommands;


import Sessions.EcomAdminRemote;
import Sessions.EcomCustomersRemote;
import entityBeans.Category;
import entityBeans.Products;
import entityBeans.Productsstore;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author SOGOBA
 */
public class ProductCommand implements InterShell{
    private ContextCommande cxtCmd;

    public ProductCommand(ContextCommande ContextCommand){
          cxtCmd =  ContextCommand;
    }

    @Override
  public Commands getName() {
        return Commands.product;
    }

    @Override
    public String getShortDescription() {
       String description = "Product management\n";
        description += "\t  : -add [name] [desc] [category ID] [Store ID]...........................create a new product\n";
        description += "\t  : -remove [product ID]......................................................delete a product\n";
        description += "\t  : [without args] ........................................list all products\n";
        description += "\t  : -id [product ID]..........................................................display specified product details\n";
        description += "\t  : -categ [categ ID].........................................................products of a specified category\n";
        description += "\t  : -store [store ID].........................................................products of a specified store\n";
        description += "\t  : -name [product name]......................................................products fitting the specified name\n";
        description += "\t  : -like [partial name]......................................................products fitting the partial name\n";
        description += "\t  : -price [max price]......................................................products with price under [max price]\n";
        return description;
    }

    @Override
    public void execute(String cmd,EcomAdminRemote ecomAdmin,EcomCustomersRemote ecomCust) throws RemoteException {
        
            List<Products> listProducts = null;
        //  EuroConvertorLocal convertor=ecomCustomerBean.getConvertor();
            StringTokenizer st = new StringTokenizer(cmd, " ");
            // Ignore cmd
            st.nextToken();          // without arg : list all stores
            if (st.countTokens() == 0) {
                if(cxtCmd.getVar("output").equals("XML")){
                listProducts = ecomCust.getProducts();
                System.out.println(getXML(ecomCust,listProducts));
                }
              else{
                 System.out.println(getText(ecomCust,listProducts));
                }
            } // With option
            else {
                String option = st.nextToken();
                // adding
                if (option.equals("-add")) {
                  if (st.countTokens() == 4) {
                    try {
                        String name = st.nextToken();
                        Double price=Double.valueOf(st.nextToken());
                        int categIg = Integer.parseInt(st.nextToken());
                        int StoreId=Integer.parseInt(st.nextToken());
                        Category cat=ecomAdmin.getCat(categIg);
                        Productsstore store=ecomAdmin.getStore(StoreId);
                        ecomAdmin.createProd(name, price,cat,store);
                        System.out.println("the product " + name + "has been succesfully created in the category " + categIg + "\n");
                        //res.append(_context.returnCode("Product Created with id #" + id, RESULT_ACTION.SUCCESS));
                    } catch (NumberFormatException | RemoteException e) {
                        //res.append(context.returnCode("Error with product creation", RESULT_ACTION.FAILED));
                        System.out.println("Error with product creation");
                    }
                } else {
                    //res.append(_context.returnCode(Shell.INCORRECT_ARGS_NUMBER, RESULT_ACTION.FAILED));
                     System.out.println("Command is not avalaible");
                }
                    } else if (option.equals("-remove")) {
                        if (st.countTokens() == 1) {
                            int idProd = Integer.valueOf(st.nextToken());
                            ecomAdmin.removeProd(idProd);
                            System.out.println("the product id " + idProd + " has been succesfully delete\n");
                            //res.append(_context.returnCode("Product #" + id + " deleted", RESULT_ACTION.SUCCESS));
                        } else {
                            //res.append(_context.returnCode(Shell.INCORRECT_ARGS_NUMBER, RESULT_ACTION.FAILED));
                            System.out.println("Command is not avalaible");
                        }
                    } else if (option.equals("-id")) {
                        if (st.countTokens() == 1) {
                            int id = Integer.valueOf(st.nextToken());
                            listProducts = new ArrayList<Products>();
                            listProducts.add(ecomCust.getProdById(id));
                            if (cxtCmd.getVar("output").equals("XML")){
                               System.out.println(getXML(ecomCust, listProducts));
                        } else{
                           System.out.println(getText(ecomCust, listProducts));

                        }
                    }
                       else {
                            System.out.println("Command is not avalaible");
                        }
                    } else if (option.equals("-categ")) {
                        if (st.countTokens()==1) {
                            int categId = Integer.valueOf(st.nextToken().trim());
                            listProducts = ecomCust.getProdByCat(categId);
                             if (cxtCmd.getVar("output").equals("XML")){
                               System.out.println(getXML(ecomCust, listProducts));
                        } else{
                           System.out.println(getText(ecomCust, listProducts));

                        }
                        }
                         else{
                               System.out.println("Command is not avalaible");
                    }
                } else if (option.equalsIgnoreCase("-store")) {
                         if (st.countTokens()==1) {
                            int storeId = Integer.valueOf(st.nextToken().trim());
                            listProducts = ecomCust.getProductsStore(storeId);
                             if (cxtCmd.getVar("output").equals("XML")){
                               System.out.println(getXML(ecomCust, listProducts));
                        } else{
                           System.out.println(getText(ecomCust, listProducts));

                        }
                        }
                         else{
                               System.out.println("Command is not avalaible");
                    }
                    } else if (option.equalsIgnoreCase("-name")) {
                        String name=st.nextToken().trim();
                        listProducts = ecomCust.getProdByName(name);
                        if (cxtCmd.getVar("output").equals("XML")){
                           System.out.println(getXML(ecomCust, listProducts));
                        } else{
                           System.out.println(getText(ecomCust, listProducts));

                        }

                    }
                     else if (option.equalsIgnoreCase("-like")) {
                        String name=st.nextToken().trim();
                        listProducts = ecomCust.getProdByNameLike(name);
                        if (cxtCmd.getVar("output").equals("XML")){
                           System.out.println(getXML(ecomCust, listProducts));
                        } else{
                           System.out.println(getText(ecomCust, listProducts));

                        }
                    } else if (option.equalsIgnoreCase("-price")) {
                        if (st.countTokens()==1){
                        Double price=Double.valueOf(st.nextToken().trim());
                        listProducts = ecomCust.getProdByPrice(price);
                        if (cxtCmd.getVar("output").equals("XML")){
                           System.out.println(getXML(ecomCust, listProducts));
                        } else{
                           System.out.println(getText(ecomCust, listProducts));
                        }
                        }
                       else if (st.countTokens()==2){
                        Double price1=Double.valueOf(st.nextToken().trim());
                        Double price2=Double.valueOf(st.nextToken().trim());
                        listProducts = ecomCust.getProdByInterPrice(price1,price2);
                        if (cxtCmd.getVar("output").equals("XML")){
                           System.out.println(getXML(ecomCust, listProducts));
                        } else{
                           System.out.println(getText(ecomCust, listProducts));

                        }
                        }else {

                            System.out.println("Command is not avalaible");
                    }
                }
            }
    }

    @SuppressWarnings("CallToThreadDumpStack")
  public String getXML(EcomCustomersRemote ecomCustomerBean, List<Products> lesProd){
        String xmlString="";
        try {
            // Create Document factory
            DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
            // Create document
            DocumentBuilder constructeur = fabrique.newDocumentBuilder();
            // Read a file XML with DOM
            File xml = new File("C:/Users/SOGOBA/Documents/NetBeansProjects/StoreEcom/StoreEcom-app-client/src/java/storeecom/XMLDocument.xml");
            Document document = constructeur.parse(xml);
            // Cr�ation de l'arborescence du DOM
            Element racine = document.getDocumentElement();
     //       racine.appendChild(document.createComment("Dysplay all products "));
            Element products = document.createElement("Products");
            racine.appendChild(products);
            // Get all products 
            for (Products prod : lesProd) {
                Element p = document.createElement("Product");
                products.appendChild(p);
                Element storeId = document.createElement("productStoreId");
                storeId.setTextContent(prod.getIdProductsstoreFk().getReferenceStore().toString());
                p.appendChild(storeId);
                Element prodId = document.createElement("reference");
                prodId.setTextContent(prod.getReferenceProd().toString());
                p.appendChild(prodId);
                Element name = document.createElement("name");
                name.setTextContent(prod.getNameProd());
                p.appendChild(name);
                Element price = document.createElement("price");
                price.setAttribute("currency", cxtCmd.getVar("currency").toString());
              //  price.setTextContent("1000");
               price.setTextContent(ecomCustomerBean.getConverToEuro(prod.getPriceProd(),cxtCmd.getVar("currency").toString()).toString());
                p.appendChild(price);
            }
                DOMSource domSource = new DOMSource(document);
                StringWriter writer = new StringWriter();
                StreamResult result = new StreamResult(writer);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.transform(domSource, result);
                xmlString = writer.toString();
        }
        catch (IOException | ParserConfigurationException ex) {
            Logger.getLogger(CustomersCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    catch(Exception e){
            e.printStackTrace();
          }
    return xmlString;
}


public String getText (EcomCustomersRemote ecomCustomerBean, List<Products> lesProd){
  String textString="List of all products  \n";
            for (Products prod : lesProd){
               textString+="Store Id : "+ prod.getIdProductsstoreFk().getReferenceStore() +"Id product : "+ prod.getReferenceProd()+ "name : "+ prod.getNameProd()+ "Price currency: "+cxtCmd.getVar("currency")+ "Value : "+ ecomCustomerBean.getConverToEuro(prod.getPriceProd(),cxtCmd.getVar("currency").toString()).toString()+ "\n";
            }
      
    return textString;
}

}
